# -*- coding:utf-8-*-
# 文件读写
import os
import io
from datetime import datetime

def isFileExist(filePath):
	return os.path.exists(filePath)

# 最简单的文件读写方法
def readFile(fileName):
	if not isFileExist(fileName):
		print "{} is not exist ".format(fileName)
		return ""
	f = open(fileName)
	content = f.read()
	f.close()
	return content

def widthReadFile(fileName,isReadLine=False):
	if not isFileExist(fileName):
		print "{} is not exist ".format(fileName)
		return ""
	with open(fileName) as f:
		# readline 读取一行
		if isReadLine:
			content = f.readline()
		else:
			content = f.read()
	return content

# 写文件
def writeToFile(filePath,fileName,content):
	if not os.path.exists(filePath):
		os.mkdir(filePath)
	fullPath = os.path.join(filePath,fileName)

	with io.open(fullPath,mode = "w+",encoding = "utf-8")as f:
		f.write(content.decode("utf-8"))
	pass

# 拆分出文件名和路径
def getFilePath(filePath):
	return os.path.split(filePath)

# 拆分出来文件路径和后缀
def getFileExt(filePath):
	return os.path.splitext(filePath)

# 获取指定后缀名文件
# key:
def find_file(path,ext=".py"):
	retList = []

	for fileName in os.listdir(path):
		#print fileName
		_,fileExt = getFileExt(fileName)
		if fileExt == ext:
			retList.append(fileName)
	return retList

def getLastModifyTime(filePath):
	if not filePath:
		return
	for root,_,files in os.walk(filePath):
		for file in files:
			fullPath = os.path.join(root,file)
			modifyTime = os.path.getmtime(fullPath)
			normalTime = datetime.fromtimestamp(modifyTime)
			print "fileName = {} last modify time = {}".format(file,normalTime)
			pass

if __name__ == "__main__":
	cwd = os.getcwd()
	print cwd

	writeToFile(cwd,"testFile.json",'''tian tian mo yu
	天天摸鱼
	百日做梦
	''')
	fileStr = widthReadFile("./testFile.json",False)
	print fileStr

	filePath,fileName =  getFilePath("{}/{}".format(cwd,"testFile.json"))
	print "filePath = {} ,fileName = {}".format(filePath,fileName)

	filePath ,fileExt =  getFileExt("{}/{}".format(cwd,"testFile.json"))
	print "filePath = {} ,fileExt = {}".format(filePath,fileExt)

	print find_file(cwd)

	getLastModifyTime(cwd)
